package controller

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"onerk4/zk1/api/enit/request"
	"onerk4/zk1/api/enit/response"
	"onerk4/zk1/dao/mysql"
	"onerk4/zk1/dao/redis"
	"onerk4/zk1/pkg"
	"onerk4/zk1/utils"
	"strconv"
)

func SendSms(c *gin.Context) {
	var req request.SendSms

	if err := c.ShouldBind(&req); err != nil {
		response.ErrorResponse(c, "参数错误", err.Error())
		return
	}

	code := rand.Intn(9000) + 1000

	ok := utils.Mobile(req.Mobile)
	if !ok {
		response.ErrorResponse(c, "手机号格式不正确", nil)
		return
	}

	//sms, _ := pkg.SendSms(req.Mobile, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	response.ErrorResponse(c, nil, *sms.Body.Message)
	//	return
	//}

	redis.SetSms(req.Mobile, req.Source, strconv.Itoa(code))

	response.SuccessResponse(c, "验证码发送成功", nil)
}

func Login(c *gin.Context) {
	var req request.Login

	if err := c.ShouldBind(&req); err != nil {
		response.ErrorResponse(c, "参数错误", err.Error())
		return
	}

	ok := utils.Mobile(req.Mobile)
	if !ok {
		response.ErrorResponse(c, "手机号格式不正确", nil)
		return
	}

	sms := redis.GetSms(req.Mobile, "Login")
	if sms != req.Sms {
		response.ErrorResponse(c, "验证码错误", nil)
		return
	}

	users, err := mysql.ShowUserByMobile(req.Mobile)
	if err != nil {
		return
	}

	if users.ID == 0 {
		response.ErrorResponse(c, "改手机号还未注册", nil)
		return
	}

	if users.Password != users.Password {
		response.ErrorResponse(c, "密码错误", nil)
		return
	}

	claims := pkg.CustomClaims{ID: uint(users.ID)}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		response.ErrorResponse(c, "token生成失败", nil)
		return
	}

	redis.DelSms(req.Mobile, "Login")

	response.SuccessResponse(c, "登入成功", token)
}
